package com.cim.web;

import com.cim.storage.StorageService;
import com.cim.utils.ResponseFileContentTypeUtil;
import com.cim.utils.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;

@Api(tags="图片相关")
@RestController
@RequestMapping("/api/image")
public class ImageController {

    @Autowired
    StorageService storageService;

    //图片上传
    @ApiOperation(value="图片上传",notes="上传并保存图片,返回图片地址")
    @PostMapping(value = "/upload",consumes = "multipart/*",headers = "content-type=multipart/form-date")
    public Object upload(@RequestParam @ApiParam(value="图片文件",name="file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String fileName=storageService.store(file.getInputStream(), file.getSize(), file.getContentType(), originalFilename);
        return ResponseUtil.ok(fileName);
    }

    //图片获取
    @ApiOperation(value="图片获取",notes="通过图片文件名获取图片")
    @GetMapping("/get")
    public void get(@RequestParam @ApiParam("图片文件名") String name,
                      HttpServletResponse response){
        Path path=storageService.load(name);
        if(path!=null){
            try {
                InputStream imgInputStream=new FileInputStream(path.toFile());
                BufferedImage img= ImageIO.read(imgInputStream);
                String format=path.toString().substring(path.toString().lastIndexOf(".")+1);
                response.setContentType(ResponseFileContentTypeUtil.get(format));  //设置返回数据格式
                ImageIO.write(img,format,response.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
